package com.wh.testReadWriteLock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * ReadWriteLock 读写锁
 *   读-读  可以共存
 *   读-写  不能共存
 *   写-写  不能共存
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCacheLock myCache = new MyCacheLock();
        for (int i = 0; i <= 10; i++) {
            final int tem = i;
            new Thread(() -> {
                myCache.put(tem + "", tem);
            }, String.valueOf(i)).start();
        }
        for (int i = 0; i <= 10; i++) {
            final int tem = i;
            new Thread(() -> {
                myCache.get(tem + "");
            }, String.valueOf(i)).start();
        }
    }
}

/**
 * 自定义缓存
 */
class MyCache {
    private volatile Map<String, Object> map = new HashMap<>();

    //存
    public void put(String key, Object value) {
        System.out.println(Thread.currentThread().getName() + "准备写入" + key);
        map.put(key, value);
        System.out.println(Thread.currentThread().getName() + "写入OK");
    }

    //取
    public void get(String key) {
        System.out.println(Thread.currentThread().getName() + "准备读取" + key);
        Object o = map.get(key);
        System.out.println(Thread.currentThread().getName() + "读取OK");
    }
}

class MyCacheLock {
    private volatile Map<String, Object> map = new HashMap<>();
    //读写锁 更加细粒度的控制
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    //存 写入的时候，只希望同时只有一个线程写
    public void put(String key, Object value) {
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "准备写入" + key);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写入OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }
    }

    //取 读，所有人都可以读!
    //读加锁是为了防止写（读加锁的时候，无法写），并不是防止脏读，脏读是写的时候读（读到其他未提交的数据）
    public void get(String key) {
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "准备读取" + key);
            Object o = map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }
    }
}
